package com.cino.basic.interceptor;

import com.cino.basic.jwt.JwtUtils;
import com.cino.basic.jwt.LoginData;
import com.cino.basic.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("token");//JWT 的token - 三部分的字符串
        if(token != null){//有登陆信息
            try {
                //解密之后获取登录信息,先用
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().
                        getResource("auth_rsa.pub").getFile());
                JwtUtils.getInfoFromToken(token,publicKey, LoginData.class);
                return true;
            } catch (ExpiredJwtException e) {
                //跳转到登录页面 - 后端跳不了，因为后端项目没有页面 - 放在前端跳转
                //告诉浏览器我要给你响应一个json数据，编码集为utf-8
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                e.printStackTrace();
                return false;
            }



        }


        return false;

    }
}